<template>
  <div class="supplier-form-content">
    <ContentHeader
      :title="supplierFormInfo?.partName"
      :tagTitle="supplierFormInfo?.formType ? FormTypeMap[supplierFormInfo?.formType] : ''"
      :tagStyle="supplierFormInfo?.formType"
    >
      <template #desc>
        <span>功能单位：{{ empty(supplierFormInfo?.num) }}{{ empty(supplierFormInfo?.unit) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>零部件编码：{{ empty(supplierFormInfo?.partCode) }}</span>
        <el-divider direction="vertical"></el-divider>
        <!-- <span
          >类型：{{
            supplierFormInfo?.formType ? FormTypeMap[supplierFormInfo?.formType] : '-'
          }}</span
        >
        <el-divider direction="vertical"></el-divider> -->
        <span>数据年份：{{ empty(supplierFormInfo?.dataYear) }}年</span>
        <el-divider direction="vertical"></el-divider>
        <span>备注：{{ empty(supplierFormInfo?.remark) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>供应商：{{ empty(supplierFormInfo?.supplierName) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>联系人：{{ empty(supplierFormInfo?.contact) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>手机号：{{ empty(supplierFormInfo?.contactPhone) }}</span>
        <div class="g-flex-side-center">
          <div class="g-font-14n2 g-mb4">同类编码：</div>
          <div class="model-tag-wrap">
            <template
              v-if="supplierFormInfo?.partSuitCode && supplierFormInfo?.partSuitCode.length"
            >
              <div
                class="model-tag"
                v-for="(item, index) in supplierFormInfo?.partSuitCode"
                :key="index"
                >{{ item }}</div
              >
            </template>
            <el-button text class="edit-icon" type="primary" @click="handleEdit" v-if="!readonly"
              >编辑</el-button
            >
          </div>
        </div>
      </template>
    </ContentHeader>

    <el-form ref="formRef" label-position="top" :model="formData" :rules="formRules">
      <el-row>
        <el-col :span="24">
          <el-form-item label="填报方式(二选一)" prop="feedbackType">
            <ComplexRadio
              v-model="formData.feedbackType"
              :disabled="readonly"
              :options="FeedbackTypeOptions"
            ></ComplexRadio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item
            label="采集周期"
            prop="range"
            :rules="dateRules"
            v-if="supplierFormInfo?.dataMonth"
          >
            <el-date-picker
              :disabled="readonly"
              v-model="formData.range"
              type="monthrange"
              range-separator="-"
              value-format="YYYY-MM"
              start-placeholder="开始月份"
              end-placeholder="截止月份"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <ContentCollapse
        :option="contentCollapseOption"
        v-if="formData.feedbackType === FeedbackTypeEnum.MANUFACTURE"
      >
        <template #BOM>
          <ProductBomList
            :formNo="props.businessKey"
            :nodeCode="supplierFormInfo?.partCode"
            :supplierFormInfo="supplierFormInfo"
            :bomCount="bomCount"
            :readonly="readonly"
          />
        </template>
        <template #SITE>
          <SiteDataList
            ref="siteDataList"
            :formNo="props.businessKey"
            :supplierFormInfo="supplierFormInfo"
            :readonly="readonly"
          />
        </template>
        <template #OTHER>
          <el-form-item label="工艺流程图" v-if="isShowDiagram">
            <g-upload
              :action="uploadFilePostUrlV3"
              :postParams="{ scope: 'inventory', needRename: 'false', groupType: 'AD_FILL_TASK' }"
              v-model:fileList="formData.fileList"
              accept=".jpg,.png,.jpeg,.pdf"
              @success="handleUploadSuccess"
              previewByApi
              :disabled="readonly"
              v-if="!(readonly && !formData.fileList?.length)"
              :limit="1000"
            >
              <template #default="{ loading: btnLoading }">
                <el-button :loading="btnLoading"
                  ><CIcon type="c-xian-shangchuan" class="g-mr4"></CIcon>上传文件</el-button
                >
              </template>
              <template #tip>
                <div class="g-ml10" style="display: inline-block">
                  <span class="g-font-12n3">支持 JPG、PNG、JPEG、PDF 格式文件，大小不超过20M</span>
                </div>
              </template>
            </g-upload>
            <span v-else>-</span>
          </el-form-item>
          <el-form-item label="工艺过程描述" v-if="isShowProcess">
            <span class="g-font-14n2" v-if="readonly">{{ empty(formData.attachmentDesc) }}</span>
            <el-input
              v-else
              style="width: 640px"
              v-model="formData.attachmentDesc"
              type="textarea"
              show-word-limit
              maxlength="255"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </template>
      </ContentCollapse>
      <div
        class="report-wrapper"
        v-if="formData.feedbackType === FeedbackTypeEnum.CERTIFICATION_REPORT"
      >
        <CollapseItemTitle title="报告信息" />
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="碳足迹因子值" prop="factor" required :rules="factorAndUnitRule">
              <CDosageAndUnit
                v-model:dosage="formData.factor"
                v-model:unit="formData.factorUnit"
                placeholder="请输入"
                :unit-option="FactorUnitOptions"
                :disabled="readonly"
              ></CDosageAndUnit>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="认证机构" prop="certificateBody">
              <el-input
                v-model="formData.certificateBody"
                placeholder="请输入"
                :disabled="readonly"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证书编号" prop="certificateNo">
              <el-input
                v-model="formData.certificateNo"
                placeholder="请输入"
                :disabled="readonly"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="认证报告" prop="fileList2">
          <g-upload
            :action="uploadFilePostUrlV3"
            :postParams="{ scope: 'inventory', needRename: 'false', groupType: 'AD_FILL_TASK' }"
            v-model:fileList="formData.fileList2"
            accept=".jpg,.png,.jpeg,.pdf"
            :disabled="readonly"
            previewByApi
            @success="handleUploadSuccess2"
            :limit="1000"
          >
            <template #default="{ loading: btnLoading }">
              <el-button :loading="btnLoading"
                ><CIcon type="c-xian-shangchuan" class="g-mr4"></CIcon>上传文件</el-button
              >
            </template>
            <template #tip>
              <div class="g-ml10" style="display: inline-block">
                <span class="g-font-14n2">支持 JPG、PNG、JPEG、PDF 格式文件，大小不超过 20M</span>
              </div>
            </template>
          </g-upload>
        </el-form-item>
      </div>
    </el-form>
    <EditCode
      v-model:visible="dialogVisible"
      :supplierFormInfo="supplierFormInfo"
      :processInstanceId="processInfo.processInstanceId"
      @refresh="getCodeData"
    ></EditCode>
  </div>
</template>
<script lang="ts">
export default {
  name: 'SupplierForm'
};
</script>
<script lang="ts" setup>
import { ref, defineExpose, defineProps, inject, computed, reactive } from 'vue';
import ContentHeader from '../../components/ContentHeader/index.vue';
import ContentCollapse from '../../components/ContentCollapse/index.vue';
import CollapseItemTitle from './components/CollapseItemTitle/index.vue';
import ProductBomList from './components/ProductBomList/index.vue';
import SiteDataList from './components/SiteDataList/index.vue';
import EditCode from './components/EditCode/index.vue';
import { ComplexRadio } from './components/ComplexRadio';

import type { TodoDetailRootProvider } from '../../types';
import { TODO_DETAIL_ROOT } from '../../types';
import {
  FeedbackTypeOptions,
  FeedbackTypeEnum,
  TaskDefinitionKeySupplierForm,
  FormTypeMap
} from '@/constants/enum';
import { formRules } from './rules';
import { uploadFilePostUrlV3 } from '@/apis/common/common';
import { useMessage } from '@/hooks/useMessage';
import { GUpload } from '@/components/GUpload';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import { FactorUnitOptions } from '@/constants/enum';
import { getSupplierFormDetail } from '@/apis/supplier/supplier';
import type { GetSupplierFormDetailResult } from '@/apis/supplier/model/supplierModel';
import { empty } from '@/utils';
import { isArray } from '@/utils/is';

interface FootprintAccountingProps {
  businessKey: string;
}
const props = defineProps<FootprintAccountingProps>();

const { pageType, processInfo } = inject(TODO_DETAIL_ROOT) as TodoDetailRootProvider;

const { createMessage } = useMessage();
const formRef = ref();

// NOTE 可以操作的状态
const canOperate = computed(() => {
  // 待办、即将超时、已超时
  return ['PENDING', 'ABOUT_TO_EXPIRE', 'OUT_OF_TIME'].includes(pageType);
});

// 展示查看组件
const readonly = computed(() => {
  // NOTE 仅回复模型需要填写表单信息
  return (
    !canOperate.value ||
    processInfo.value?.taskDefinitionKey !== TaskDefinitionKeySupplierForm.SF_DATA_FILL
  );
});

const dialogVisible = ref(false);
const handleEdit = () => {
  dialogVisible.value = true;
};
/**
 * 折叠面板配置
 */
const siteDataList = ref();
const headerRightFormState = computed(() => {
  return siteDataList.value?.headerRightFormState;
});
const contentCollapseOption = computed(() => {
  if (isShowOther.value) {
    return {
      collapseOptions: [
        {
          title: '零部件BOM清单',
          key: 'BOM',
          defaultOpened: true
        },
        {
          title: '零部件生产场地数据',
          key: 'SITE',
          desc: readonly.value
            ? `以下数据对应 ${headerRightFormState.value?.productNum}${headerRightFormState.value?.productUnit} 零部件`
            : '',
          defaultOpened: true
        },
        {
          title: '其他信息',
          desc: '辅助审核',
          key: 'OTHER',
          defaultOpened: true
        }
      ]
    };
  } else {
    return {
      collapseOptions: [
        {
          title: '零部件BOM清单',
          key: 'BOM',
          defaultOpened: true
        },
        {
          title: '零部件生产场地数据',
          key: 'SITE',
          desc: readonly.value
            ? `以下数据对应 ${headerRightFormState.value?.productNum}${headerRightFormState.value?.productUnit} 零部件`
            : '',
          defaultOpened: true
        }
      ]
    };
  }
});

const supplierFormInfo = ref({} as GetSupplierFormDetailResult);
async function getCodeData() {
  try {
    supplierFormInfo.value = await getSupplierFormDetail(props.businessKey);
    formData.partSuitCode = supplierFormInfo.value.partSuitCode;
  } catch (error) {
    console.log('error', error);
  }
}
const validateDate = (rule: any, value: any, callback: any) => {
  if (value && isArray(value) && value.length) {
    if (value.join(',').includes(supplierFormInfo.value?.dataYear as string)) {
      callback();
    } else {
      callback(new Error(`采集周期需要包含数据年份:${supplierFormInfo.value?.dataYear}`));
    }
  } else {
    callback(new Error('必填项'));
  }
};

const dateRules = [
  {
    validator: validateDate,
    trigger: ['submit', 'blur', 'change']
  }
];
async function getData() {
  try {
    const res = await getSupplierFormDetail(props.businessKey);
    supplierFormInfo.value = res;
    formData.feedbackType = res.feedbackType || FeedbackTypeEnum.MANUFACTURE;
    formData.partSuitCode = res.partSuitCode;
    formData.factor = res.factor;
    formData.factorUnit = res.factorUnit;
    formData.certificateNo = res.certificateNo;
    if (res.dataMonth) {
      formData.range = [res.dataMonth.startMonth, res.dataMonth.endMonth];
    }
    if (res.feedbackType === 'MANUFACTURE') {
      formData.certificateBody = '';
      formData.attachmentDesc = res.attachmentDesc;
    } else if (res.feedbackType === 'CERTIFICATION_REPORT') {
      formData.certificateBody = res.attachmentDesc;
      formData.attachmentDesc = '';
    }
    if (res.attachmentName && res.attachmentUrl) {
      if (formData.feedbackType === 'MANUFACTURE') {
        formData.fileList = [
          {
            name: res.attachmentName,
            url: res.attachmentUrl
          }
        ];
      } else if (formData.feedbackType === 'CERTIFICATION_REPORT') {
        formData.fileList2 = [
          {
            name: res.attachmentName,
            url: res.attachmentUrl
          }
        ];
      } else {
        formData.fileList = [];
        formData.fileList2 = [];
      }
    } else {
      formData.fileList = [];
      formData.fileList2 = [];
    }
  } catch (error) {
    console.log('error', error);
  }
}

getData();
const formData = reactive({
  feedbackType: FeedbackTypeEnum.MANUFACTURE as keyof typeof FeedbackTypeEnum,
  factor: '',
  factorUnit: '',
  // 工艺过程描述
  attachmentDesc: '',
  // 认证机构
  certificateBody: '',
  certificateNo: '',
  partSuitCode: [] as string[],
  // 工艺流程图
  fileList: [] as any[],
  // 认证报告
  fileList2: [] as any[],
  range: [] as string[]
});

const handleUploadSuccess = (file: any) => {
  const { name, response } = file;
  if (file.response.msg == '成功') {
    const currentFile: any = formData.fileList.find((n: any) => n.uid === file.uid);
    // 将url塞入fileList
    const url = currentFile?.response?.data?.fileUrl;
    url && currentFile && (currentFile.url = url);
    createMessage.success('上传成功');
  } else {
    createMessage.info('上传失败');
  }
  console.log('handleUploadSuccess', formData.fileList);
  // uploadRef.value?.clearFiles();
};
const handleUploadSuccess2 = (file: any) => {
  const { name, response } = file;
  if (file.response.msg == '成功') {
    const currentFile: any = formData.fileList2.find((n: any) => n.uid === file.uid);
    // 将url塞入fileList2
    const url = currentFile?.response?.data?.fileUrl;
    url && currentFile && (currentFile.url = url);
    createMessage.success('上传成功');
  } else {
    createMessage.info('上传失败');
  }
  console.log('handleUploadSuccess', formData.fileList2);
  // uploadRef.value?.clearFiles();
};

function handleSubmitValid(needValidForm: boolean) {
  console.log('formData', formData);
  console.log('fileList2', formData.fileList2);
  return new Promise((resolve, reject) => {
    if (needValidForm) {
      formRef.value?.validate((valid: boolean) => {
        if (valid) {
          const params = getParams();
          console.log('params', params);
          resolve(params);
        } else {
          reject();
        }
      });
    } else {
      const params = getParams();
      resolve(params);
    }
  });
}

/**
 * 碳足迹因子值和单位的校验
 */
const validatorFactorAndUnit = (rule: any, value: any, callback: any) => {
  if (!formData.factor) {
    callback(new Error('必填项'));
  } else if (!formData.factorUnit) {
    callback(new Error('请选择单位'));
  } else {
    callback();
  }
};

const factorAndUnitRule = [
  {
    validator: validatorFactorAndUnit,
    trigger: ['change', 'blur', 'submit']
  }
];

function getParams() {
  let attachmentName = '',
    attachmentUrl = '',
    attachmentDesc = '';
  // 场地数据
  if (formData.feedbackType === 'MANUFACTURE') {
    if (formData.fileList?.length) {
      attachmentName = formData.fileList[0].name;
      attachmentUrl = formData.fileList[0].url;
    }
    attachmentDesc = formData.attachmentDesc;
  } else if (formData.feedbackType === 'CERTIFICATION_REPORT') {
    if (formData.fileList2?.length) {
      attachmentName = formData.fileList2[0].name;
      attachmentUrl = formData.fileList2[0].url;
    }
    attachmentDesc = formData.certificateBody;
  }
  const params = {
    feedbackType: formData.feedbackType,
    factor: formData.factor,
    factorUnit: formData.factorUnit,
    certificateNo: formData.certificateNo,
    attachmentDesc: attachmentDesc,
    attachmentName: attachmentName,
    attachmentUrl: attachmentUrl,
    partSuitCode: formData.partSuitCode
  };
  if (formData.range && formData.range.length) {
    Object.assign(params, {
      dataMonth: {
        startMonth: formData.range[0],
        endMonth: formData.range[1]
      }
    });
  }
  return params;
}

function submit(needValidForm = true) {
  return handleSubmitValid(needValidForm);
}

// 详情状态下是否展示 工艺流程图
const isShowDiagram = computed(() => {
  return !(readonly.value && !formData.fileList?.length);
});
// 详情状态下是否展示 工艺过程描述
const isShowProcess = computed(() => {
  if (readonly.value) {
    return formData.attachmentDesc ? true : false;
  } else {
    return true;
  }
});
// 详情状态下是否展示 其他信息栏位
const isShowOther = computed(() => {
  return isShowDiagram.value || isShowProcess.value;
});

defineExpose({
  submit
});
</script>
<style lang="scss" scoped>
.supplier-form-content {
  padding: 32px 32px 0;
}
:deep(.supplier-form-collapse.el-collapse) {
  --el-collapse-border-color: #f2f3f5;
  .el-collapse-item {
    .el-collapse-item__header {
      height: 56px;
    }
    .el-form-item .el-form-item__label {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #0a1f33;
      line-height: 22px;
    }
  }
}

.report-wrapper {
  border-top: 1px solid #f2f3f5;
}

.supplier-form-feedback-type-icon {
  color: #96a7b3;
  &:hover {
    color: #03ac82;
  }
}

.model-tag {
  min-width: 36px;
  height: 20px;
  padding: 0 6px;
  line-height: 20px;
  text-align: center;
  background: #eef1f5;
  border-radius: 3px;
  font-size: 12px;
  color: #5a739a;
  margin-top: 4px;
  margin-right: 4px;
}
.model-tag-wrap {
  display: flex;
  flex-wrap: wrap;
}
.edit-icon {
  margin-left: 4px;
  cursor: pointer;
}
</style>
